package com.zdx.yswl.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.zdx.yswl.Constant;
import com.zdx.yswl.R;
import com.zdx.yswl.base.KException;
import com.zdx.yswl.http.KAsyncTask.TaskDelegate;
import com.zdx.yswl.tool.KLog;
import com.zdx.yswl.tool.KNetTool;
import com.zdx.yswl.tool.KSystemTool;
import com.zdx.yswl.ui.adapter.BuildViewPagerAdapter;
import com.zdx.yswl.ui.adapter.BuildViewPagerAdapter.OnClickPagerListener;
import com.zdx.yswl.ui.adapter.LpInfoAdapter;
import com.zdx.yswl.ui.base.BaseActivity;
import com.zdx.yswl.ui.base.BaseWebViewActivity;
import com.zdx.yswl.ui.bean.BannerBean;
import com.zdx.yswl.ui.bean.LpBean;
import com.zdx.yswl.ui.exception.NetworkException;
import com.zdx.yswl.ui.exception.NoDataException;
import com.zdx.yswl.ui.task.BannerTask;
import com.zdx.yswl.ui.task.LifedooTask;
import com.zdx.yswl.ui.task.LpInfoTask;

public class MainActivity extends BaseActivity implements TaskDelegate, OnClickListener {

	
	protected static final String TAG = MainActivity.class.getSimpleName();
	protected static final int bannerTaskId = 10001;
	protected static final int buildTaskId = 10002;
	protected static final int lifedooTaskId = 10003;

	LpInfoAdapter adapter;
	ListView listView;

	private ImageView[] indicator_imgs;
	private ScheduledExecutorService scheduledExecutorService;// 定时周期执行指定任务
	private ViewPager mViewpager;
	private RelativeLayout viewpagerLayout;
	private int currentPage = -1;// 当前页
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mViewpager.setCurrentItem(currentPage);
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		UmengUpdateAgent.update(this);
		initNav();

		initData();
	}

	private void initNav() {
		setHeader("楼盘");
		super.mBack.setVisibility(View.INVISIBLE);
		super.mRight.setVisibility(View.VISIBLE);
		if (!KNetTool.isNetworkConnected(this)) {
			Toast.makeText(this, "无网络，请检查", Toast.LENGTH_LONG).show();
			return;
		}
		super.mRight.setOnClickListener(this);

		
	}

	private void initData() {
		viewpagerLayout = (RelativeLayout) findViewById(R.id.viewpager_layout);
		listView = (ListView) findViewById(R.id.lp_listview);
		mViewpager = (ViewPager) findViewById(R.id.view_pager);
		LinearLayout mCam = (LinearLayout) findViewById(R.id.my_cam_btn);
		mCam.setOnClickListener(this);

		viewpagerLayout.setVisibility(View.GONE);
		listView.setVisibility(View.GONE);

		adapter = new LpInfoAdapter(this);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				LpBean bean = adapter.getItem(position);
				Intent detailIntent = DetailActivity.actionStart(MainActivity.this, bean.id, bean.projectName);
				detailIntent.putExtra("projectId", bean.id);
				startActivity(detailIntent);
			}
		});

		super.startProgress();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("bindId", Constant.bindId);
		BannerTask banner = new BannerTask(bannerTaskId, this);
		banner.execute(map);
		LpInfoTask task = new LpInfoTask(buildTaskId, this);
		task.execute(map);

		if (KLog.isShow == true) {
			KSystemTool.getDeviceInfo(this);// 友盟统计
		}
	}

	private void initViewPager(final ArrayList<BannerBean> list) {
		BuildViewPagerAdapter mAdapter = new BuildViewPagerAdapter(this, list);
		mAdapter.setAdaperOnClickListener(new OnClickPagerListener() {
			@Override
			public void onClikPager(View v) {
				int position = (Integer) v.getTag();
				// Toast.makeText(MainActivity.this, "点击了--" + v.getTag(),
				// Toast.LENGTH_SHORT).show();
				BannerBean bean = list.get(position);
				String name = getNameById(bean.id);// 根据id查找 name;

				if (bean.type == 0) { // 跳转 link 指定的h5
				// Toast.makeText(MainActivity.this, "跳转 link 指定的h5",
				// Toast.LENGTH_SHORT).show();
					if (!bean.link.contains("http:")) {
						bean.link = "http:" + bean.link;
					}
					Intent intent = BaseWebViewActivity.createIntent(MainActivity.this, bean.link, name, false, true);
					startActivity(intent);
				} else if (bean.type == 1) {// 跳转楼盘详情页
				// Toast.makeText(MainActivity.this, "跳转楼盘详情页",
				// Toast.LENGTH_SHORT).show();
					Intent detailIntent = DetailActivity.actionStart(MainActivity.this, bean.projectId, name);
					startActivity(detailIntent);
				}
			}
		});
		mViewpager.setAdapter(mAdapter);
		mViewpager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				currentPage = position;// 临时
				// 改变所有导航的背景图片为：未选中
				for (int i = 0; i < indicator_imgs.length; i++) {
					indicator_imgs[i].setBackgroundResource(R.drawable.indicator);
				}
				// 改变当前背景图片为：选中
				indicator_imgs[position % list.size()].setBackgroundResource(R.drawable.indicator_focused);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				synchronized (mViewpager) {
					handler.sendEmptyMessage(++currentPage);
				}
			}
		}, 1000, 5000, TimeUnit.MILLISECONDS);

		// 进度点
		LinearLayout view = (LinearLayout) findViewById(R.id.indicator);
		for (int i = 0; i < list.size(); i++) {
			indicator_imgs[i] = new ImageView(this);
			LinearLayout.LayoutParams params_linear = new LinearLayout.LayoutParams(10, 10);
			params_linear.setMargins(7, 10, 7, 10);
			indicator_imgs[i].setLayoutParams(params_linear);
			if (i == 0) {
				// 初始化第一个为选中状态
				indicator_imgs[i].setBackgroundResource(R.drawable.indicator_focused);
			} else {
				indicator_imgs[i].setBackgroundResource(R.drawable.indicator);
			}
			((LinearLayout) view).addView(indicator_imgs[i]);
		}

	}

	/** 友盟session的统计 */
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	/** 友盟session的统计 */
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.my_cam_btn) {
//			startActivity(new Intent(this, DevMainActivity.class));
			//------跳转url------//
			new LifedooTask(this, lifedooTaskId, this).execute();
		} else if (R.id.nav_right == v.getId()) {
			Intent intent = new Intent(MainActivity.this, SetActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void faild_TaskDelegate(int taskId, Object object) {
		super.closeProgress();
		if (object instanceof NoDataException) {
			Toast.makeText(this, ((NoDataException) object).getMessage(), Toast.LENGTH_SHORT).show();
		} else if (object instanceof NetworkException) {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		} else if (object instanceof KException) {
			Toast.makeText(this, ((KException) object).getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void success_TaskDelegate(int taskId, Object object) {
		super.closeProgress();
		if (taskId == bannerTaskId) {
			viewpagerLayout.setVisibility(View.VISIBLE);
			ArrayList<BannerBean> list = (ArrayList<BannerBean>) object;
			indicator_imgs = new ImageView[list.size()];
			initViewPager(list);
		} else if (taskId == buildTaskId) {
			listView.setVisibility(View.VISIBLE);
			adapter.dataList = (ArrayList<LpBean>) object;
			adapter.notifyDataSetChanged();
		} else if(taskId == lifedooTaskId){
			String url = object.toString();
			Intent intent = BaseWebViewActivity.createIntent(MainActivity.this, url, "LifeDoo", false,true);
			startActivity(intent);
		}
	}

	private long mExitTime;

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			} else {
				exitApp();
				System.exit(0);

			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private String getNameById(String id) {
		if (adapter.dataList == null) {
			return "楼盘详情";
		}

		for (int i = 0; i < adapter.dataList.size(); i++) {
			if (adapter.dataList.get(i).id.equalsIgnoreCase(id)) {
				return adapter.dataList.get(i).projectName;
			}

		}
		return "楼盘详情";
	}

	@Override
	public void onNotify(int what, int arg1, int arg2, Object obj) {

	}

	@Override
	public void onHandler(int what, int arg1, int arg2, Object obj) {

	}

	@Override
	protected void initSettings() {

	}

	@Override
	protected void initUi() {

	}

	@Override
	protected void saveSettings() {

	}

	@Override
	protected void freeMe() 
	{
	}
}
